using System.Text.Json;
using DeathReportManagement.Models;

namespace DeathReportManagement.Services;

public class ReportSubmissionService
{
    private readonly IHttpClientFactory _httpClientFactory;
    private readonly IConfiguration _configuration;
    private readonly OperationLogService _operationLogService;
    
    public ReportSubmissionService(
        IHttpClientFactory httpClientFactory, 
        IConfiguration configuration,
        OperationLogService operationLogService)
    {
        _httpClientFactory = httpClientFactory;
        _configuration = configuration;
        _operationLogService = operationLogService;
    }
    
    public async Task<SubmissionResult> SubmitSubReportAsync(DeathReport report, int userId)
    {
        try
        {
            var reportData = PrepareReportData(report, "SUB");
            var result = await SendReportAsync(reportData, "sub-report");
            
            if (result.Success)
            {
                await _operationLogService.LogAsync(
                    report.Id, 
                    "附联上报成功", 
                    userId, 
                    $"上报流水号: {result.ReferenceNumber}");
            }
            else
            {
                await _operationLogService.LogAsync(
                    report.Id, 
                    "附联上报失败", 
                    userId, 
                    $"错误信息: {result.ErrorMessage}");
            }
            
            return result;
        }
        catch (Exception ex)
        {
            await _operationLogService.LogAsync(
                report.Id, 
                "附联上报异常", 
                userId, 
                $"异常信息: {ex.Message}");
            
            return new SubmissionResult
            {
                Success = false,
                ErrorMessage = $"上报时发生异常: {ex.Message}"
            };
        }
    }
    
    public async Task<SubmissionResult> SubmitMainReportAsync(DeathReport report, int userId)
    {
        try
        {
            var reportData = PrepareReportData(report, "MAIN");
            var result = await SendReportAsync(reportData, "main-report");
            
            if (result.Success)
            {
                await _operationLogService.LogAsync(
                    report.Id, 
                    "主联上报成功", 
                    userId, 
                    $"上报流水号: {result.ReferenceNumber}");
            }
            else
            {
                await _operationLogService.LogAsync(
                    report.Id, 
                    "主联上报失败", 
                    userId, 
                    $"错误信息: {result.ErrorMessage}");
            }
            
            return result;
        }
        catch (Exception ex)
        {
            await _operationLogService.LogAsync(
                report.Id, 
                "主联上报异常", 
                userId, 
                $"异常信息: {ex.Message}");
            
            return new SubmissionResult
            {
                Success = false,
                ErrorMessage = $"上报时发生异常: {ex.Message}"
            };
        }
    }
    
    private object PrepareReportData(DeathReport report, string reportType)
    {
        return new
        {
            reportNo = report.ReportNo,
            reportType = reportType,
            deceasedInfo = new
            {
                name = report.DeceasedName,
                gender = report.Gender,
                ethnicity = report.Ethnicity,
                idType = report.IdType,
                idNumber = report.IdNumber,
                birthDate = report.BirthDate.ToString("yyyy-MM-dd"),
                age = report.Age,
                ageUnit = report.AgeUnit,
                maritalStatus = report.MaritalStatus,
                education = report.Education,
                personalIdentity = report.PersonalIdentity,
                workUnit = report.WorkUnit
            },
            deathInfo = new
            {
                deathDateTime = report.DeathDateTime.ToString("yyyy-MM-dd HH:mm:ss"),
                deathLocation = report.DeathLocation,
                isPregnant = report.IsPregnant
            },
            addressInfo = new
            {
                householdAddressType = report.HouseholdAddressType,
                householdAddress = report.HouseholdAddress,
                householdDetailAddress = report.HouseholdDetailAddress,
                residenceAddressType = report.ResidenceAddressType,
                residenceAddress = report.ResidenceAddress,
                residenceDetailAddress = report.ResidenceDetailAddress
            },
            contactInfo = new
            {
                name = report.ContactName,
                phone = report.ContactPhone,
                idType = report.ContactIdType
            },
            submitTime = DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss")
        };
    }
    
    private async Task<SubmissionResult> SendReportAsync(object reportData, string endpoint)
    {
        var healthDepartmentApiUrl = _configuration["ReportSettings:HealthDepartmentApiUrl"];
        var apiKey = _configuration["ReportSettings:ApiKey"];
        
        if (string.IsNullOrWhiteSpace(healthDepartmentApiUrl))
        {
            return await SimulateSubmissionAsync();
        }
        
        try
        {
            var httpClient = _httpClientFactory.CreateClient();
            httpClient.Timeout = TimeSpan.FromSeconds(30);
            
            if (!string.IsNullOrWhiteSpace(apiKey))
            {
                httpClient.DefaultRequestHeaders.Add("X-API-Key", apiKey);
            }
            
            var json = JsonSerializer.Serialize(reportData);
            var content = new StringContent(json, System.Text.Encoding.UTF8, "application/json");
            
            var response = await httpClient.PostAsync($"{healthDepartmentApiUrl}/api/{endpoint}", content);
            
            if (response.IsSuccessStatusCode)
            {
                var responseContent = await response.Content.ReadAsStringAsync();
                var responseData = JsonSerializer.Deserialize<SubmissionResponse>(responseContent);
                
                return new SubmissionResult
                {
                    Success = true,
                    ReferenceNumber = responseData?.ReferenceNumber ?? Guid.NewGuid().ToString("N")[..12].ToUpper()
                };
            }
            else
            {
                var errorContent = await response.Content.ReadAsStringAsync();
                return new SubmissionResult
                {
                    Success = false,
                    ErrorMessage = $"HTTP {(int)response.StatusCode}: {errorContent}"
                };
            }
        }
        catch (HttpRequestException ex)
        {
            return new SubmissionResult
            {
                Success = false,
                ErrorMessage = $"网络错误: {ex.Message}"
            };
        }
        catch (TaskCanceledException ex)
        {
            return new SubmissionResult
            {
                Success = false,
                ErrorMessage = ex.InnerException is TimeoutException ? "请求超时" : "请求被取消"
            };
        }
    }
    
    private async Task<SubmissionResult> SimulateSubmissionAsync()
    {
        await Task.Delay(1000);
        
        return new SubmissionResult
        {
            Success = true,
            ReferenceNumber = DateTime.Now.ToString("yyyyMMddHHmmss") + Random.Shared.Next(1000, 9999)
        };
    }
}

public class SubmissionResult
{
    public bool Success { get; set; }
    public string? ErrorMessage { get; set; }
    public string? ReferenceNumber { get; set; }
}

public class SubmissionResponse
{
    public string? ReferenceNumber { get; set; }
    public string? Message { get; set; }
    public bool Success { get; set; }
}